<?php

namespace app\api\logic;
use  app\api\logic\BasicLogic;
use app\common\library\RedissLock;
use app\common\service\CommonExportCsvTaskLogService;
use app\common\service\CommonSystemImportService;
use app\common\service\JinyiApiService;
use app\data\util\HttpUtil;
use app\data\util\MqQueueName;
use app\systems\logic\MqTaskPushLogic;
use think\facade\Db;

class TestLogic extends BasicLogic
{
    /**
     * @desc  本地excel数据上传异步操作
     * @author luckyXiong
     * @Date   2024/03/20 10:55
     */
    public function uploadExcelTest($params){
        try{
            $result = CommonSystemImportService::staticModel()->operate_import_data([
                    $this,//当前对应的service
                    'save',//类型: template 下载模板; save :保存 导入
                    CommonSystemImportService::TYPE_IMPORT_INCOMPLETE_TIME,
                    1,
                    $params
                ]
            );
        }catch (\Exception $e) {
            return $this->jsonMessage(201, false, $e->getMessage(), null);
        }
    }




    /**
     * @desc 将导入数据写入目标表
     * @author xx
     * @date 2024-03-21
     */
    public function import_time_detail($params=[]){
         $key = 'import_time_detail:'.time();
         $redis_lock = new RedissLock();
         $lock = $redis_lock::lock($key, $redis_lock::UNBLOCK, 300);
         $order_number =   getIsset($params,'order_number');
         $shop_name    =   getIsset($params,'shop_name');
         $sku          =   getIsset($params,'sku');
         $num          =   getIsset($params,'num');
         $buyer_email  =   getIsset($params,'buyer_email');
         $buyer_name   =   getIsset($params,'buyer_name');
         $address      =   getIsset($params,'address');
         $city         =   getIsset($params,'city');
         $state        =   getIsset($params,'state');
         $post_code    =   getIsset($params,'post_code');
         $country      =   getIsset($params,'country');
         $phone        =   getIsset($params,'phone');

        $parts         =   explode('-', $order_number);  // 使用explode函数将字符串按照 "-" 分割成数组
        $order_id      =   end($parts);

        //数据入库逻辑
        $info = [
            'order_id'           =>$order_id,
            'order_number'       =>$order_number,
            'sku'                =>$sku,
            'num'                =>$num,
            'shop_name'          =>$shop_name,
            'buyer_email'        =>$buyer_email,
            'buyer_name'         =>$buyer_name,
            'address'            =>$address,
            'city'               =>$city,
            'state'              =>$state,
            'post_code'          =>$post_code,
            'country'            =>$country,
            'phone'              =>$phone,
            'create_time'        =>date("Y-m-d H:i:s", time()),
        ];
        //update 2024-08-27
        $res = Db::name('order_history_list')->insertGetId($info);
        $lock->unlock();
        $info['status'] = $res == 1 ? 1:2;
        return  $info;
    }


    /**
     * @param $row
     * @return string[]
     * @desc 数据title 导入组装数据结构
     */
    public function get_excel_row_data($row){
        return [
            'order_number'      => empty($row['A'])? '': trim($row['A']),
            'shop_name'         => empty($row['B'])? '': trim($row['B']),
            'sku'               => empty($row['D'])? '': trim($row['D']),
            'num'               => empty($row['C'])? '': trim($row['C']),
            'buyer_email'       => empty($row['E'])? '': trim($row['E']),
            'buyer_name'        => empty($row['F'])? '': trim($row['F']),
            'address'           => empty($row['G'])? '': trim($row['G']),
            'city'              => empty($row['H'])? '': trim($row['H']),
            'state'             => empty($row['I'])? '': trim($row['I']),
            'post_code'         => empty($row['J'])? '': trim($row['J']),
            'country'           => empty($row['K'])? '': trim($row['K']),
            'phone'             => empty($row['L'])? '': trim($row['L']),
        ];
    }




    /**
     * @desc  数据清洗
     * @author xx
     * @date 2024-07-10
     */
    public function shopify_change($order){
           $order_id             = $order['order_id']??'';
           $honey_order_number   = $order['honey_order_number']??'';
           if(!$order_id)  return true;
           $field    = 'order_id,sku,order_number as honey_order_number,shop_name,num,buyer_name,buyer_email,address,city,state,post_code,phone,country,create_time';
           $where    = [];
           $where[]  = ['order_id','=',$order_id];
           $time_start = date('Y-m-d 00:00:00');
           $time_end   = date('Y-m-d 23:59:59');
           $where[]    = ['create_time','between', [$time_start, $time_end]];
           $list     = Db::name('order_history_list')->field($field)->where($where)->select()->toArray();
           $map = [];
           $map[]   = ['order_id','=',$order_id];
           $map[]   = ['address','<>',''];
           $map[]   = ['create_time','between', [$time_start, $time_end]];
           $current = Db::name('order_history_list')->field($field)->where($map)->find();
           $arr     = [];
           foreach($list as $v){
                   if(strpos($v['sku'], ',') !== false){
                       $skuInfo = $v['sku'];
                   }else{
                       $skuInfo = self::get_seller_sku($v['sku'],$v['num']);
                   }

                   $temp = [
                       'order_id'        =>$v['order_id'],
                       'sku'             =>$skuInfo,
                       'num'             =>$v['num'],
                   ];
               $arr[] =$temp;
           }

        $skus = [];
        $num = 0;
        $arr = self::get_unique_sku($arr);
        foreach($arr as $v){
                $num+= $v['num'];
                if(preg_match('/.*-(\d+)$/', $v['sku'], $matches)){
                    $skus[] = $v['sku'];
                }else{
                    $skus[] = $v['num'] > 1 ? $v['sku'].'-'.$v['num'] : $v['sku'];
                }
        }

        //update 2024-07-15,数据匹配发货仓库;
        $check_res      = self::get_inventory_hwc($skus);
        $shop_infos     = Config('Logisticskey.shop_info');
        $shop_id        = $shop_infos[$current['shop_name']]??'';
        if($shop_id){
            $order_id_info  = Db::name('order')->field('order_id,shop_id')->where(['order_number'=>$order_id,'shop_id'=>$shop_id])->find();
        }else{
            $order_id_info  = Db::name('order')->field('order_id,shop_id')->where('order_number',$order_id)->find();
        }
        if(!$order_id_info)  return  '订单数据未拉取!';
        $newOrders = [
            'order_id'             =>$order_id_info['order_id'],
            'order_number'         =>$order_id,
            'honey_order_number'   =>$honey_order_number,
            'sku'                  =>implode(',',$skus),
            'num'                  =>$num,
            'shop_id'              =>$order_id_info['shop_id'],
            'shop_name'            =>$current['shop_name'],
            'buyer_name'           =>$current['buyer_name'],
            'buyer_email'          =>$current['buyer_email'],
            'address'              =>$current['address'],
            'city'                 =>$current['city'],
            'state'                =>$current['state'],
            'post_code'            =>$current['post_code'],
            'phone'                =>$current['phone'],
            'country'              =>$current['country'],
            'create_time'          =>date("Y-m-d H:i:s", time()),
        ];

        if($check_res){
            $newOrders['ship_status']       = 8;
            $newOrders['warehouse_id_plan'] = $check_res;
        }

        // 2024-08-28 手机号为空补全0
        if(!$newOrders['phone']){
            $newOrders['phone'] = '0000000000';
        }
        $exist_info = Db::name('order_shopify_list')->where('order_id',$order_id_info['order_id'])->value('id');
        if(empty($exist_info)){
            Db::name('order_shopify_list')->insert($newOrders);
        }
        return  true;
    }




    /**
     * @desc   匹配获取可以发货的库存数据
     * @author luckyXiong
     * @date   2024-07-15
     * @title  匹配规则,优先顺丰仓库，单件走jjs，然后金蚁
     */
    public function get_inventory_hwc($skus){
        $warehouse_id = 0;
        $arr          = [];
        foreach($skus as $v){
            $arr[] = self::get_sku_num($v);
        }
        // 查询每个 SKU 的当前库存数量
        foreach ($arr as $v) {
            $sellerSku       = $v['sku'];
            $num             = $v['num'];
            $currentQuantity = Db::name('inventory_hwc')
                ->where('new_quantity','>=',$num)
                ->where('sku',$sellerSku)
                ->value('new_quantity');
            $currentQuantity = $currentQuantity ?: '';
            // 记录每个 SKU 的库存状态
            $inventoryCheck[$sellerSku] = $currentQuantity;
        }
        // 匹配所有的sku库存状态;
        $check_res = self::checkArrayValues($inventoryCheck);
        if(!$check_res){
            return  $warehouse_id;
        }else{
            // 如果所有 SKU 验证成功，进行库存扣减
            foreach ($arr as $v) {
                // 执行库存更新
                self::incStock($v['sku'],$v['num']);
            }
            return  3;
        }
    }


    /**
     * @desc   扣减库存处理
     * @author luckyXiong
     * @date   2024-12-25
     */
    public function incStock($seller_sku,$num){
        Db::name('inventory_hwc')
            ->where('new_quantity','>=',$num)
            ->where('sku',$seller_sku)
            ->dec('new_quantity', $num)
            ->update();
    }






    /**
     * @desc   匹配获取可以发货的江夏仓库
     * @author luckyXiong
     * @date   2024-12-25
     * @title  匹配规则,优先顺丰仓库，单件走jjs，然后金蚁
     */
    public function get_inventory_jxc($skus,$id){
        $warehouse_id = 0;
        $arr  =  $few_sku_info = $need_sku_arr =  $inventoryCheck = $arr_sku = [];
        foreach($skus as $v){
            $arr[] = self::get_sku_num_jxc($v);
        }

        // 查询每个 SKU 的当前库存数量
        foreach ($arr as $v) {
            $sellerSku = trim($v['sku']);
            $num       = $v['num'];
            $currentQuantity = Db::name('product_inventory')
                ->where('seller_sku',$sellerSku)
                ->value('inventory_quantity');
            $currentQuantity = $currentQuantity ?: '';
            //无库存的
            if (empty($currentQuantity)) {
                $need_sku_arr[]   = $sellerSku.'-'.$num;
            }else{
                // 检查库存不足
                if($currentQuantity && $currentQuantity < $num) {
                    $nums = ($num-$currentQuantity);
                   $few_sku_info[] = $sellerSku.'-'.$nums;
                }else{
                    // 记录每个 SKU 的库存状态
                    $inventoryCheck[$sellerSku] = $currentQuantity;
                }
            }

        }
        // 匹配所有的sku库存状态;
        $check_res = self::checkArrayValues($inventoryCheck);
        if(!$check_res){
            // 更新缺货信息;
            Db::name('checkbill_888')->where(['id'=>$id])->update([
                'few_sku_info' =>$few_sku_info ? implode(',',$few_sku_info) : '',
                'need_sku_info'=>$need_sku_arr ? implode(',',$need_sku_arr) : '',
            ]);
            return  $warehouse_id;
        }else{
            // 如果所有 SKU 验证成功，进行库存扣减
            foreach ($arr as $v) {
                $sellerSku = $v['sku'];
                // 执行库存更新
                Db::name('product_inventory')
                    ->where('inventory_quantity','>=',$v['num'])
                    ->where('seller_sku', $sellerSku)
                    ->dec('inventory_quantity', $v['num'])
                    ->update();
            }
            return  1;
        }
    }


   //检测是否够相应的库存扣减
   private function checkArrayValues($array) {
        foreach ($array as $value) {
            // 检查当前值是否为空
            if (empty($value)) {
                return false; // 如果值为空，返回 false
            }
        }
        return true;
    }








    /**
     * @desc  更新库存处理
     * @author xx
     * @date 2024-07-15
     */
    private function change_new_quantity($info=[]){
        if(!$info)  return  '';
        $num = $info['num']??0;
        $sku = $info['sku']??'';
        $new_quantity =$info['inventory_quantity']??0;
        $where   = [];
        $where[] = ['seller_sku','=',$sku];
        Db::name('product_inventory')->where($where)->update(
            [
                'inventory_quantity'=>$new_quantity-$num,
            ]
        );
    }



    /**
     * @desc   orders
     * @author xx
     * @date 2025-04-17
     */
    public function  test_hwc_order($params){
            htmlLog(['params'=>$params],OPERATE_LOG . date('Ym') . '/test_hwc_order/' . date('Ymd') . '.txt');
            $order_id  = $params['order_id']??'';
            $info      = Db::name('order_info')
                ->field('id,shop_id,order_id,sku,spu,quantity as num')
                ->where(['order_id'=>$order_id])
                ->where('sku','<>','')
                ->where('is_seel','<>',1)
                ->select()
                ->toArray();
            $arr = $temp = $list = $infos = [];

            $country = Db::name('order_process')->where(['order_id'=>$order_id])->value('country');
            if($country!='US'){
                return  true;
            }


            // first update 2025-04-12 数据优先全量匹配
            $all_sku_res = self::get_all_sku($info);


            if($all_sku_res==1){ //可以匹配全量
                return  true;
            }


            //second 匹配可以满足2件sku拆单的
            foreach ($info as $v) {
                $pattern = '/\+/';
                if (!preg_match($pattern, $v['sku'])) { // 仅处理不含加号的条目
                    $pos = strpos($v['sku'], '/');
                    if ($pos !== false) {
                        $sku = substr($v['sku'], 0, $pos);
                    }else{
                        $sku = $v['sku'];
                    }
                    $list[] = [
                        'order_id' => $v['order_id'],
                        'shop_id'  => $v['shop_id'],
                        'spu'      => $v['spu'],
                        'sku'      => $sku,
                        'num'      => $v['num'],
                    ];
                }
            }




           $arr = array_filter($list, function($item){
               return !empty($item); // 只保留非空数组
            });


            if(!$arr)   {
                htmlLog(['params'=>$order_id],OPERATE_LOG . date('Ym') . '/test_hwc_order/' . date('Ymd') . '.txt');
                return    true;
            }

            //匹配海外仓库存数据
            // 查询每个 SKU 的当前库存数量
            $spus         = array_column($arr,'spu');
            $spus         = array_unique($spus);
            $hwc_spus     = Config('Logisticskey.hwc_sku');

            $intersection = array_intersect($spus, $hwc_spus);
            if(!$intersection)   return          '暂未匹配到spu!';
            $sum = 0;
            foreach($arr as  $v){
                $new_quantity = Db::name('inventory_hwc')
                    ->where('new_quantity','>=',$v['num'])
                    ->where('sku',$v['sku'])
                    ->order('new_quantity desc')
                    ->value('new_quantity');
                if($new_quantity){
                    $sum+=$v['num'];
                }
            }

            $current  = current($arr);


            //获取需要发货商品的总件数;
            $all_sums = array_sum(array_column($info,'num'));
           // update 2025-04-02 匹配2件及以上的sku信息;
           if($sum>1){
                //此时扣减库存
                foreach($arr as $k=>$v){
                    self::incStock($v['sku'],$v['num']);
                    $infos[$k]['sku'] = self::get_seller_sku($v['sku'],$v['num']);
                }
                $skus  = array_column($infos,'sku');
                //匹配2件及以上的订单数据;
                self::add_split_hwc($current,$skus,$all_sums);
                //同时将数据推到拆单队列;
                //update 2025-04-12 同时数据推送到拆分接口队列;
                MqTaskPushLogic::mq_task_push(
                    '',
                    MqQueueName::QUEUE_ORDER_HWC_SPLIT_QUEUE,
                    [
                        'order_id' => $current['order_id'],
                        'shop_id'  => $current['shop_id']
                    ],
                    false
              );

         }

         // update 2025-05-22 匹配1件且spu 在 ['sha01','sha41','sha14','bra10','bra86'];
        if ($sum == 1) {
            // 定义有效SKU的数组
            $single_skus = Config('Logisticskey.single_hwc');
            // 判断是否有有效的SKU
            if (array_intersect($spus, $single_skus)) {
                // 扣减库存并获取 SKU 信息
                foreach ($arr as $k => $v) {
                    self::incStock($v['sku'], $v['num']);
                    $infos[$k]['sku'] = self::get_seller_sku($v['sku'], $v['num']);
                }

                // 从信息中提取SKU
                $skus = array_column($infos, 'sku');

                // 匹配1件及以上的订单数据
                self::add_split_hwc($current, $skus, $all_sums);

                // 将数据推送到拆单队列
                MqTaskPushLogic::mq_task_push(
                    '',
                    MqQueueName::QUEUE_ORDER_HWC_SPLIT_QUEUE,
                    [
                        'order_id' => $current['order_id'],
                        'shop_id' => $current['shop_id']
                    ],
                    false
                );
            }
        }
        return   true;
    }


    /**
     * @desc  匹配全量sku
     * @author xx
     * @date 2025-04-10
     */
    public function get_all_sku($info){
        $arr = [];
        foreach($info as $v){
            $skuInfo = self::get_seller_sku($v['sku'],$v['num']);
            $temp = [
                'order_id'        =>$v['order_id'],
                'shop_id'         =>$v['shop_id'],
                'spu'             =>$v['spu'],
                'sku'             =>$skuInfo,
                'num'             =>$v['num'],
            ];
            $arr[] =$temp;
        }

        // 查询每个 SKU 的当前库存数量
        $spus         = array_column($arr,'spu');
        $spus         = array_unique($spus);
        $hwc_spus     = Config('Logisticskey.hwc_sku');

        $intersection = array_intersect($spus, $hwc_spus);
        if(!$intersection)   return          '暂未匹配到spu!';
        $infos = [];
        foreach ($arr as $v) {
            if(strpos($v['sku'], ',') !== false){
                $sellerSku = explode(',',$v['sku']);
            }else{
                $sellerSku = [$v['sku']];
            }

            foreach($sellerSku as $value){
                if( preg_match('/(.*?)(\d+)$/', $value, $matches)){
                    $nonNumericPart   = isset($matches[1]) ? rtrim($matches[1], '-') : '';
                    $numericPart      = isset($matches[2]) ? $matches[2] : '';
                    $temp['sku'] = $nonNumericPart;
                    $temp['num'] = $numericPart;
                }else{
                    $temp['sku'] = $value;
                    $temp['num'] = $v['num'];
                }
                $infos[] = $temp;
            }
        }

        foreach($infos as $k=>$v){
            $pos = strpos($v['sku'], '/');
            if ($pos !== false) {
                $infos[$k]['sku'] = substr($v['sku'], 0, $pos);
            }
        }

        $sum = 0;
        foreach($infos as  $v){
            $new_quantity = Db::name('inventory_hwc')
                ->where('new_quantity','>=',$v['num'])
                ->where('sku',$v['sku'])
                ->order('new_quantity desc')
                ->value('new_quantity');
            if($new_quantity){
                $sum+=$v['num'];
                self::incStock($v['sku'],$v['num']);
            }
        }


        $all_sums = array_sum(array_column($infos,'num'));
        $skus  = array_column($infos,'sku');
        if($sum == $all_sums){
            //全量匹配订单;多件或单件,组装全量匹配发货数据;
            self::add_all_hwc($infos,$skus,$all_sums);
            return  1;
        }
        return  '';
    }





    /**
     * @desc  数据清洗生产
     * @author xx
     * @date 2024-07-10
     */
    public function get_sku_num($sku=''){
            $sku_info = explode('-',$sku);
            $num = isset($sku_info[3])&& $sku_info[3] ? $sku_info[3] : 1;
            if(in_array($sku_info[2],['XL/2XL','3XL/4XL','4XL/5XL','5XL/6XL','6XL/7XL'])){
                $parts = explode('/', $sku_info[2]);
                $sku_info[2] =$parts[0]??'';
            }
            $sku_value = $sku_info[0].'-'.$sku_info[1].'-'.$sku_info[2];
            return  ['num'=>$num,'sku'=>$sku_value];
    }


    /**
     * @desc  数据清洗生产
     * @author xx
     * @date 2024-12-10
     */
    public function get_sku_num_jxc($sku=''){
        $sku_info  = explode('-',$sku);
        $num       = isset($sku_info[3])&& $sku_info[3] ? $sku_info[3] : 1;
        $sku_value = $sku_info[0].'-'.$sku_info[1].'-'.$sku_info[2];
        return  ['num'=>$num,'sku'=>$sku_value];
    }



    /**
     * @desc   匹配全量海外仓数据
     * @author xx
     * @date  2025-04-12
     */
    public function add_all_hwc($arr,$skus,$all_sums){
        $arr = self::get_unique_sku($arr);
        //update 2025-08-22 匹配唯一性;
        $skus = array_unique($skus);
        foreach($arr as $k=>$v){
            if(preg_match('/.*-(\d+)$/', $v['sku'], $matches)){
                $skus[$k] = $v['sku'];
            }else{
                $skus[$k] = $v['num'] > 1 ? $v['sku'].'-'.$v['num'] : $v['sku'];
            }
        }

        $shop_names           = Config('Logisticskey.shop_names');
        $shop_numbers         = Config('Logisticskey.shop_number');
        $current_info         = current($arr);
        $number               = $shop_numbers[$current_info['shop_id']]??'7256335';
        $order_name           = Db::name('order')->where(['order_id'=>$current_info['order_id']])->value('order_number');
        $order_number         = $number.'-'.$order_name;
        $info                 = Db::name('order_shipping')
                                ->where(['order_id'=>$current_info['order_id']])
                                ->find();
        $email                = Db::name('order_customer')
                                ->where(['order_id'=>$current_info['order_id']])
                                ->value('email');
        $first_name           = $info['first_name']??'';
        $last_name            = $info['last_name']??'';

        $address1             = $info['address1']??'';
        $address2             = $info['address2']??'';

        $address              = $address1;
        if($address2){
            $address = $address1.' '.$address2;
        }


        $insert_info = [
            'order_id'           => $current_info['order_id'],
            'order_number'       => $order_name,
            'honey_order_number' => $order_number,
            'sku'                => implode(',',$skus),
            'num'                => $all_sums,
            'shop_id'            => $current_info['shop_id'],
            'shop_name'          => $shop_names[$current_info['shop_id']]??'',
            'buyer_name'         => $first_name.' '.$last_name,
            'buyer_email'        => $email??'',
            'address'            => $address,
            'city'               => $info['city']??'',
            'state'              => $info['province']??'',
            'post_code'          => $info['zip']??'',
            'phone'              => $info['phone']??'0000000000',
            'country'            => $info['country']??'',
            'split_status'       => 0,
            'warehouse_id'       => 3,
            'ship_status'        => 8,
            'create_time'        => date("Y-m-d H:i:s"),
            'update_time'        => date("Y-m-d H:i:s"),
            'warehouse_id_plan'  => 3,
        ];
        $exist_info = Db::name('order_shopify_list')->where(['order_id'=>$current_info['order_id']])->find();
        if(!$exist_info){
            Db::name('order_shopify_list')->insert($insert_info);
        }
        return  true;
    }



    /**
     * @desc   匹配全量海外仓数据
     * @author xx
     * @date  2025-04-12
     */
    public function add_split_hwc($current,$skus,$all_sums){
        $shop_numbers         = Config('Logisticskey.shop_number');
        $number               = $shop_numbers[$current['shop_id']]??'7256335';
        $order_name           = Db::name('order')->where(['order_id'=>$current['order_id']])->value('order_number');
        $order_number         = $number.'-'.$order_name;
        $sku_list = [
            'order_id'     =>$current['order_id']??'',
            'shop_id'      =>$current['shop_id']??'',
            'order_number' =>$order_number,
            'spu'          =>$current['spu']??'',
            'sku'          =>implode(',',$skus),
            'num'          =>$all_sums,
            'sku_type'     =>2,
            'create_time'  =>date("Y-m-d H:i:s", time()),
        ];

        $exist_info = Db::name('order_explode')->where(['order_id'=>$current['order_id']])->find();
        if(!$exist_info){
            Db::name('order_explode')->insert($sku_list);
        }
        return  true;
    }







    /**
     * @desc  数据清洗生产
     * @author xx
     * @date 2024-07-10
     */
    public function shopifyChangePru(){
        //获取当天时间的数据
        $where                   = [];
        $time_start              = date('Y-m-d 00:00:00');
        $time_end                = date('Y-m-d 23:59:59');
        $where[]                 = ['create_time','between', [$time_start, $time_end]];
        $list                    = Db::name('order_history_list')->field('id,order_id,order_number as honey_order_number')->where($where)->group('order_id')->select();
        $list                    = objectToArray($list);
        if(!$list)    return '暂无数据!';
        foreach($list as $v){
               //推动数据到队列;
               MqTaskPushLogic::mq_task_push(
                   '',
                   MqQueueName::QUEUE_TIK_ORDER_SHOPIFY_CHANGE_QUEUE,
                   $v,
               false
               );
           }
        $num = count($list);
        return '预发货处理数据'.$num.'条';
    }


    /**
     * @desc   导出数据处理
     * @author xx
     * @date   2024-08-10
     */
    public function exportUrl(){
        //获取导出数据
        $where                   = [];
        $time_start              = date('Y-m-d 00:00:00');
        $time_end                = date('Y-m-d 23:59:59');
        $where[]                 = ['created_unix','between', [strtotime($time_start), strtotime($time_end)]];
        $where[]                 = ['status','=', 1];
        $info_id                 = Db::name('common_export_csv_task_log')->where($where)->value('id');
        if(!$info_id)            return   '暂无数据';
        $list                    = Db::name('common_export_csv_create_info')
            ->field('task_done_no')
            ->where(['export_csv_task_id'=>$info_id])
            ->whereIn('status',[0,1])
            ->select()
            ->toArray();
        if(!$list)       return   '暂无数据';
        foreach($list as &$v){
           (new CommonExportCsvTaskLogService())->createCsvConsumer(
                [
                    'export_csv_task_id'=> $info_id,
                    'task_done_no'      => $v['task_done_no'],
                ]
            );
        }
        return '操作完成';
    }

    /**
     * @desc   导出数据处理
     * @author xx
     * @date   2024-08-10
     */
    public function get_shopify_sku($order_id){
        $info      = Db::name('order_info')
            ->field('id,shop_id,order_id,sku,spu,quantity as num')
            ->where(['order_id'=>$order_id])
            ->where('sku','<>','')
            ->where('is_seel','<>',1)
            ->select()
            ->toArray();

        $arr       = [];
        foreach($info as $v){
            $skuInfo = self::get_seller_sku($v['sku'],$v['num']);
            $temp = [
                'order_id'        =>$v['order_id'],
                'shop_id'         =>$v['shop_id'],
                'spu'             =>$v['spu'],
                'sku'             =>$skuInfo,
                'num'             =>$v['num'],
            ];
            $arr[] =$temp;
        }

        $infos = [];
        foreach ($arr as $v) {
            if(strpos($v['sku'], ',') !== false){
                $sellerSku = explode(',',$v['sku']);
            }else{
                $sellerSku = [$v['sku']];
            }

            foreach($sellerSku as $value){
                if( preg_match('/(.*?)(\d+)$/', $value, $matches)){
                    $nonNumericPart   = isset($matches[1]) ? rtrim($matches[1], '-') : '';
                    $numericPart      = isset($matches[2]) ? $matches[2] : '';
                    $temp['sku'] = $nonNumericPart;
                    $temp['num'] = $numericPart;
                }else{
                    $temp['sku'] = $value;
                    $temp['num'] = $v['num'];
                }
                $infos[] = $temp;
            }
        }

        foreach($infos as $k=>$v){
            $pos = strpos($v['sku'], '/');
            if ($pos !== false) {
                $infos[$k]['sku'] = substr($v['sku'], 0, $pos);
            }
        }
        $skus = [];
        $arr = self::get_unique_sku($infos);
        foreach($arr as $k=>$v){
            if(preg_match('/.*-(\d+)$/', $v['sku'], $matches)){
                $skus[$k] = $v['sku'];
            }else{
                $skus[$k] = $v['num'] > 1 ? $v['sku'].'-'.$v['num'] : $v['sku'];
            }
        }
        return  $skus;
    }




    /**
     * @desc  数据清洗生产
     * @author xx
     * @date 2024-07-10
     */
    public function get_seller_sku($sku,$num=1){
        return get_shopify_spu($sku,$num);
    }

    /**
     * @desc  get_unique_sku
     * @author xx
     * @date 2024-07-13
     */
    public function get_unique_sku($orders=[]){
        // 新数组
        $newOrders = [];
        // 循环原始数组，拆分并合并sku，并累加num值
        foreach ($orders as $order) {
            $skus = explode(',', $order['sku']);
            foreach ($skus as $sku) {
                $key = $order['order_id'] . '-' . $sku;
                if (isset($newOrders[$key])) {
                    // 如果已经存在相同订单和SKU的记录，累加num值
                    $newOrders[$key]['num'] += $order['num'];
                }else{
                    // 新的订单和SKU，直接加入新数组
                    $newOrders[$key] =[
                        'order_id' => $order['order_id'],
                        'shop_id'  => $order['shop_id'],
                        'sku'      => $sku,
                        'num'      => $order['num'],
                    ];
                }
            }
        }
        return  array_values($newOrders);
    }



    /**
     * @desc    获取物流单号推送到shopify
     * @author luckyXiong
     * @date   2024-07-12
     */
    public function trackShopify($order=[]){
        $order_id        = $order['order_id']??'';
        $tracking_number = $order['tracking_number']??'';
        $shop_id         = $order['shop_id']??'';
        $fulfillment_order_id = $order['fullment_order_id']??'';
        if(empty($fulfillment_order_id)){
            $fulfillment_order_id = Db::name('order_shopify_list')->where('order_id',$order_id)->value('fullment_order_id');
        }
        $shop_info       = Db::name('shops')->where('id',$shop_id)->find();
        if(!$tracking_number)    return '物流单号不能为空!';
        if(!$fulfillment_order_id){
            $url                  = $shop_info['myshopify_domain'] .Config('Logisticskey.shopify.create_fullment_id').$order_id."/fulfillment_orders.json";
            $fulfillment_orders   = HttpUtil::getUrl($url, $shop_info);
            if(!isset($fulfillment_orders['fulfillment_orders'][0]['id']) || empty($fulfillment_orders['fulfillment_orders'][0]['id']))  return  '暂无fullment_id';
            //物流id
            $fulfillment_order_id = $fulfillment_orders['fulfillment_orders'][0]['id'];
        }

        Db::name('order_shopify_list')->where('order_id',$order_id)->update(
            ['fullment_order_id'=>$fulfillment_order_id]
        );

        //同时查看拆单详情表是否有数据
        $exist_explode_info = Db::name('order_explode_detail')->where(['order_id'=>$order_id,'hwc_warehouse'=>1])->find();
        if($exist_explode_info){
            Db::name('order_explode_detail')->where('id',$exist_explode_info['id'])->update(
                ['track_number'=>$tracking_number]
            );
        }

        // 创建物流信息
        $fulfill_url = $shop_info['myshopify_domain'] . Config('Logisticskey.shopify.create_tracking_path');
        $data_fulfillments = [
            'fulfillment'         => [
                'notify_customer' => true,
                'tracking_info' => [
                    'company'   => 'USPS',
                    'number'    => $tracking_number,
                ],
                'line_items_by_fulfillment_order' => [
                    0 => [
                        'fulfillment_order_id' => $fulfillment_order_id,
                    ],
                ],
            ],
        ];
        $return = HttpUtil::PostUrl($fulfill_url, $data_fulfillments, $shop_info);
        $res  = json_decode($return, true);
        htmlLog(['respose'=>$res,'fulfillment_order_id'=>$fulfillment_order_id],OPERATE_LOG . date('Ym') . '/trackShopify/' . date('Ymd') . '.txt');
        return  true;
    }



    /**
     * @desc   获取物流单号推送到shopify生产方法
     * @author luckyXiong
     * @date   2024-07-12
     */
    public function trackShopifyProduce($params=[]){
        $field       = 'order_id,shop_id,tracking_number,fullment_order_id';
        $where       = [];
        $time_start  = date('Y-m-d 00:00:00');
        $time_end    = date('Y-m-d 23:59:59');
        $where[]     = ['create_time','between', [$time_start, $time_end]];
        $list        = Db::name('order_shopify_list')->field($field)->where($where)->select();
        $list        = objectToArray($list);
        if(!$list)  return   '暂无数据';
        foreach($list as $v){
            MqTaskPushLogic::mq_task_push(
                '',
                MqQueueName::QUEUE_TIK_TRACK_TO_SHOPIFY_QUEUE,
                $v,
                false
            );
        }
    }




    /**
     * @desc   获取物流单号推送到shopify生产方法
     * @author luckyXiong
     * @date   2024-07-12
     */
    public function change_order(){
         $t1       = microtime(true);
         $list =Db::name('inventory_hwc')->field('id,sku')->select()->toArray();
         echo PHP_EOL . '开始' . PHP_EOL;
         foreach($list as $k=>$v){
                 echo PHP_EOL . '执行第' .($k+1).'条'. PHP_EOL;
                 $seller_sku_arr           = explode('-',$v['sku']);
                 $spu                      = $seller_sku_arr[0]??'';
                 Db::name('inventory_hwc')->where('id',$v['id'])->update(['spu'=>$spu]);
        echo  PHP_EOL . '结束' . PHP_EOL;
        echo  PHP_EOL ."get_create_time-定时执行总耗时:".round( microtime(true) - $t1, 3). PHP_EOL;
       }
    }


    /**
     * @desc   库存管理SPU数据统计
     * @author luckyXiong
     * @date   2024-07-26
     */
    public function get_inventory(){
           $list = Db::name('product_inventory')->field('id,spu,product_name,warehouse')
                    ->group('spu')
                    ->order('spu desc')
                    ->select()->toArray();
           $arr = [];
           foreach($list as $v){
                   //获取单spu的数量;
                   $info = Db::name('product_inventory')
                           ->field('spu,inventory_quantity,on_way_quantity,not_send_quantity,all_inventory_quantity')
                           ->where(['spu'=>$v['spu']])
                           ->select()
                           ->toArray();
                   $inventory_quantity      = array_sum(array_column($info, 'inventory_quantity'));
                   $on_way_quantity         = array_sum(array_column($info, 'on_way_quantity'));
                   $not_send_quantity       = array_sum(array_column($info, 'not_send_quantity'));
                   $all_inventory_quantity  = array_sum(array_column($info, 'all_inventory_quantity'));
                   $temp = [
                       'spu'                    =>$v['spu'],
                       'product_name'           =>$v['product_name'],
                       'inventory_quantity'     =>$inventory_quantity,
                       'on_way_quantity'        =>$on_way_quantity,
                       'not_send_quantity'      =>$not_send_quantity,
                       'all_inventory_quantity' =>$all_inventory_quantity,
                       'warehouse'              =>$v['warehouse'],
                       'create_time'            =>date("Y-m-d H:i:s", time()),
                   ];
               $arr[] = $temp;
           }
           Db::name('product_spu_inventory')->insertAll($arr);
    }



    /**
     * @desc   近30天sku销量排行
     * @author luckyXiong
     * @date   2024-08-14
     */
    public function spu_thirty_days(){
        $t1       = microtime(true);
        $list     = Db::name('product')->field('id,spu')->select()->toArray();
        echo PHP_EOL . '开始' . PHP_EOL;
        foreach($list as $k=>$v){
            echo PHP_EOL . '执行第' .($k+1).'条'. PHP_EOL;
            $thirty_days_nums = self::spu_30days($v['spu']);
            if($thirty_days_nums['skuquantity']){
                $update_info = [
                    'spu_30days'=>$thirty_days_nums['skuquantity']
                ];
                if($thirty_days_nums['skuquantity']<5)
                $update_info['product_status'] = 3;
                Db::name('product')->where('id',$v['id'])->update($update_info);
            }
            echo PHP_EOL . '结束' . PHP_EOL;
        }
        echo  PHP_EOL ."get_create_time-定时执行总耗时:".round( microtime(true) - $t1, 3). PHP_EOL;
    }



    /**
     * @desc   清洗数据spu
     * @author luckyXiong
     * @date   2024-08-21
     */
    public function get_batch_send_order(){
           $t1       = microtime(true);
           $where    = [];
           $spu_info = Db::name('product')->field('id,max_weight,min_weight,spu')->where($where)->group('spu')->select()->toArray();
           foreach($spu_info as $k=>$v){
               echo PHP_EOL . '执行第' .($k+1).'条'. PHP_EOL;
               $weight = 0;
               if($v['max_weight'] && $v['min_weight']){
                   $weight = $v['max_weight'];
                   $weight  = getRes($weight);
               }

               if($v['max_weight'] && !$v['min_weight']){
                   $weight  = $v['max_weight'];
               }

               if(!$v['max_weight'] && $v['min_weight']){
                   $weight  = $v['min_weight'];
               }

               if(!$weight){
                   continue;
               }

               Db::name('product_spu_weight')->where('id',$v['id'])->update([
                       'weight'      => $weight ? $weight*1000 : 0,
                       'create_time' => date("Y-m-d H:i:s", time()),
               ]);
               echo PHP_EOL . '结束' . PHP_EOL;
           }
        echo  PHP_EOL ."get_create_time-定时执行总耗时:".round( microtime(true) - $t1, 3). PHP_EOL;
    }


    //获取sku信息;
    public function get_sku_info($order_id){
            $info = Db::name('order_info')->field('sku')->where('order_id',$order_id)->select()->toArray();
            $arr = [];
            if($info){
               $sku = array_column($info,'sku');
                foreach($sku as $item){
                    $parts = preg_split('/[-+]/', $item);
                    // 获取第一个部分
                    $arr[] = $parts[0];
                }
                $arr = array_unique($arr);
                $spu = implode(',',$arr);
                $data['sku'] = implode(',',$sku);
                $data['spu'] = $spu;
            }else{
               $data['sku']  = '';
               $data['spu']  = '';
            }
            return  $data;
     }


    //获取spu
    public function get_spu($sku=''){
           if(!$sku)  return  '';
           $arr = [];
           if(strpos($sku,',')){
               $sku = explode(',',$sku);
               foreach($sku as $item){
                   $parts = preg_split('/[-+]/', $item);
                   // 获取第一个部分
                   $arr[] = $parts[0];
               }
               $arr = array_unique($arr);
               $res = implode(',',$arr);
           }else{
               $parts = preg_split('/[-+]/', $sku);
               // 获取第一个部分
               $arr[] = $parts[0];
               $arr = array_unique($arr);
               $res = implode(',',$arr);
           }
          return  $res;
    }


    /**
     * @desc   更新spu销量
     * @author luckyXiong
     * @date   2024-08-15
     */
    public function spuMonthConsumer($params)
    {
        $id        = $params['id'] ?? '';
        $spu       = $params['spu'] ?? '';
        $GrowthRate       = self::GrowthRate($spu);
        $three_days_nums  = self::get_3days($spu);
        $seven_days_nums  = self::spu_7days($spu);
        $thirty_days_nums = self::spu_30days($spu);
        $sixty_days_nums  = self::get_60days($spu);
        $update_info = [
            'spu_3days'  => $three_days_nums,
            'spu_7days'  => $seven_days_nums,
            'spu_30days' => $thirty_days_nums,
            'GrowthRate' => $GrowthRate,
        ];

        //新品 30天内上架产品
        $published_time = $params['published_time']??'';
        if(!$published_time) return ['msg'=>'刊登时间为空!'];
        $published_time = strtotime($published_time);

        // $published_time+180天 和当前时间对比;
        $update_time = $published_time+86400*30;
        if(time()< $update_time){
            $update_info['product_new'] = 1;
        }else{
            $update_info['product_new'] = 0;
        }

        //热卖 30天平均出单件数>100
        if($thirty_days_nums>100){
            $update_info['product_sales'] = 2;
        }else{
            $update_info['product_sales'] = 0;
        }

        //滞销 60天平均出单件数<10
        if($sixty_days_nums<10){
            $update_info['product_status'] = 3;
        }else{
            $update_info['product_status'] = 1;
        }
        Db::name('product')->where('id',$id)->update($update_info);
        return  true;
    }



    /**
     * @desc   获取一月的spu销量
     * @author luckyXiong
     * @date   2024-08-14
     */
    private function spu_30days($spu=''){
        if(!$spu)  return  0;
        $yesterday    = strtotime(date('Y-m-d', time() - timezone()));
        $yesterdayEnd = strtotime(date('Y-m-d', strtotime('-29 day') - timezone()));
        $where[]     = ['a.spu','=', $spu];
        $where[]     = ['c.createtime','between', [$yesterdayEnd, $yesterday]];
        $where[]     = ['c.financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];
        $info = Db::name('order_skuinfo')
            ->field('sum(a.realcount) as skuquantity,a.spu')
            ->alias('a')
            ->join('qu_order c','a.order_id = c.order_id', 'left')
            ->where($where)
            ->find();
        return $info['skuquantity']??0;
    }


    /**
     * @desc   获取7天的spu销量
     * @author luckyXiong
     * @date   2024-12-03
     */
    private function spu_7days($spu=''){
        if(!$spu)  return  0;
        $yesterday    = strtotime(date('Y-m-d', time() - timezone()));
        $yesterdayEnd = strtotime(date('Y-m-d', strtotime('-6 day') - timezone()));
        $where[]     = ['a.spu','=', $spu];
        $where[]     = ['c.createtime','between', [$yesterdayEnd, $yesterday]];
        $where[]     = ['c.financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];
        $info = Db::name('order_skuinfo')
            ->field('sum(a.realcount) as skuquantity,a.spu')
            ->alias('a')
            ->join('qu_order c','a.order_id = c.order_id', 'left')
            ->where($where)
            ->find();
        return $info['skuquantity']??0;
}

    /**
     * @desc   获取3天的spu销量
     * @author luckyXiong
     * @date   2024-12-03
     */
    private function get_3days($spu=''){
        if(!$spu)  return  0;
        $yesterday    = strtotime(date('Y-m-d', time() - timezone()));
        $yesterdayEnd = strtotime(date('Y-m-d', strtotime('-2 day') - timezone()));
        $where[]     = ['a.spu','=', $spu];
        $where[]     = ['c.createtime','between', [$yesterdayEnd, $yesterday]];
        $where[]     = ['c.financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];
        $info = Db::name('order_skuinfo')
            ->field('sum(a.realcount) as skuquantity,a.spu')
            ->alias('a')
            ->join('qu_order c','a.order_id = c.order_id', 'left')
            ->where($where)
            ->find();
        return $info['skuquantity']??0;
    }

    /**
     * @desc   昨日增长率
     * @author zhangheng
     * @date   2024-12-16
     */
    private function GrowthRate($spu=''){
        $where       = [];
        $yesterday   = date('Y-m-d', time() - timezone() - 24*3600);
        $time_start  = strtotime($yesterday . ' 00:00:00');
        $time_end    = strtotime($yesterday . ' 23:59:59');
        $where[]     = ['c.createtime','between', [$time_start, $time_end]];
        $where[]     = ['c.financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];
        $where[]     = ['a.spu','=', $spu];
        $info = Db::name('order_skuinfo')
            ->field('
                sum(a.realcount) as skuquantity,
                a.spu
            ')
            ->alias('a')
            ->join('qu_order c','a.order_id = c.order_id', 'left')
            ->where($where)
            ->group('a.spu')
            ->order('skuquantity desc')
            ->select()->toarray();
        $skuquantity = $info[0]['skuquantity']??0;

        $where_last       = [];
        $yesterday   = date('Y-m-d', time() - timezone() - 24*3600*2);
        $time_start  = strtotime($yesterday . ' 00:00:00');
        $time_end    = strtotime($yesterday . ' 23:59:59');
        $where_last[]     = ['c.createtime','between', [$time_start, $time_end]];
        $where_last[]     = ['c.financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];
        $where_last[]     = ['a.spu','=', $spu];
        $info_last = Db::name('order_skuinfo')
            ->field('
                sum(a.realcount) as skuquantity,
                a.spu
            ')
            ->alias('a')
            ->join('qu_order c','a.order_id = c.order_id', 'left')
            ->where($where_last)
            ->group('a.spu')
            ->order('skuquantity desc')
            ->select()->toarray();
        $skuquantity_last = $info_last[0]['skuquantity']??0;
        // 增长率
        if(empty($skuquantity_last)){
            return "0%";
        }else{
            $GrowthRate = ($skuquantity - $skuquantity_last) / $skuquantity_last * 100;
            $GrowthRate = getRes($GrowthRate)."%" ?? "0%";
            return $GrowthRate;
        }
    }

    /**
     * @desc   获取60天的spu销量
     * @author luckyXiong
     * @date   2024-12-03
     */
    private function get_60days($spu=''){
        if(!$spu)  return  0;
        $yesterday    = strtotime(date('Y-m-d', time() - timezone()));
        $yesterdayEnd = strtotime(date('Y-m-d', strtotime('-59 day') - timezone()));
        $where[]     = ['a.spu','=', $spu];
        $where[]     = ['c.createtime','between', [$yesterdayEnd, $yesterday]];
        $where[]     = ['c.financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];
        $info = Db::name('order_skuinfo')
            ->field('sum(a.realcount) as skuquantity,a.spu')
            ->alias('a')
            ->join('qu_order c','a.order_id = c.order_id', 'left')
            ->where($where)
            ->find();
        return $info['skuquantity']??0;
    }



    /**
     * @desc   获取一月的spu销量
     * @author luckyXiong
     * @date   2024-08-15
     */
    public function spuMonthProduce(){
        $list     = Db::name('product')->field('id,spu,published_time')->select()->toArray();
        foreach($list as $v){
            //推动数据到队列;
            MqTaskPushLogic::mq_task_push(
                '',
                MqQueueName::QUEUE_ORDER_SPU_MONTH_QUEUE,
                $v,
                false
              );
            }

        }




    /**
     * @desc    获取spu单价
     * @date    2024/8/28
     * @author  luckyXiong
     */
    public function get_spu_price($spu=''){
        $where   = $map = $arr = [];
        $where[] = ['skuquantity','=',1];
        $where[] = ['spu','=',$spu];
        $where[] = ['country_code','=','US'];
        $where[] = ['total_price','>',0];
        $res     = Db::name('order_achievement')->where($where)->order('total_price asc')->value('total_price');
        if(!$res){
            $map[] = ['skuquantity','=',2];
            $map[] = ['spu','=',$spu];
            $map[] = ['country_code','=','US'];
            $map[] = ['total_price','>',0];
            $result = Db::name('order_achievement')->where($map)->order('total_price asc')->value('total_price');
            $res    = $result/2;
            if($res){
                $res = getRes($res);
            }
        }

        if(!$res){
            $arr[] = ['skuquantity','=',3];
            $arr[] = ['spu','=',$spu];
            $arr[] = ['country_code','=','US'];
            $arr[] = ['total_price','>',0];
            $result = Db::name('order_achievement')->where($arr)->order('total_price asc')->value('total_price');
            $res    = $result/3;
            if($res){
                $res = getRes($res);
            }
        }

        if(!$res){
            $res = '';
        }

        return  $res;
    }


    /**
     * @desc    产品历史数据处理
     * @author  luckyXiong
     * @date    2024-12-06
     */
    public function product_history_produce(){
        $list = Db::name('listing_shop_product')->field('id,shop_id,product_shopify_id as product_id')
                ->where('id','>','1')
                ->select()->toArray();
        foreach($list as $v){
            //推动数据到队列;
            MqTaskPushLogic::mq_task_push(
                '',
                MqQueueName::QUEUE_PRODUCT_HISTORY_QUEUE,
                [
                    'product_id'=>$v['product_id'],
                    'shop_id'   =>$v['shop_id'],
                ],
                false
            );
        }
        return $this->jsonMessage(200, true, "操作成功!", '');
    }


    /**
     * @desc    海外仓数据处理
     * @author  luckyXiong
     * @date    2024-12-06
     */
    public function product_hwc_produce(){
        $where        = [];
        $list = Db::name('order_process')
            ->where($where)
            ->field('id,order_id')
            ->select()
            ->toArray();

        foreach($list as $v){
            //推动数据到队列;
            MqTaskPushLogic::mq_task_push(
                '',
                MqQueueName::QUEUE_ORDER_HWC_QUEUE,
                [
                    'id'       => $v['id'],
                    'order_id' => $v['order_id'],
                ],
                false
            );
        }
        return $this->jsonMessage(200, true, "操作成功!", '');
    }







    





















}